import socket


def scan_ports(target_host, start_port, end_port):
    open_ports = []
    for port in range(start_port, end_port + 1):
        # 1、创建套接字
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.settimeout(1)
        try:
            # 3、尝试连接该服务器及端口
            s.connect((target_host, target_port))
            open_ports.append(port)
            # 4、打印开放端口
            print(f'端口：{target_port}开放')
        except (socket.timeout, socket.error):
            print(f'端口{target_port}是关闭的')
            # 5、关闭套接字
        finally:
            s.close()
    return open_ports


# 2、获取扫描服务器的ip和端口
target_host = input('请输入您要连接的主机：')
target_port = int(input('请输入您要连接的ip：'))
start_port = 8080
end_port = 9090

# 端口扫描函数
open_ports = scan_ports(target_host, start_port, end_port)

if open_ports:
    print(f'{target_host}地址上的开放端口有{open_ports}')
else:
    print(f'当前ip端口未开放')
